// 选择用户
const app = getApp()

import {
  mergeArray,
  type
} from '../../../js/newUtil';
import {
  router
} from '../../../js/router'
import {
  api
} from '../../../js/util';
import {
  customer
} from '../../../js/modules/customer'

import BasePage from '../../../js/common/base-page'
import { getFuzzyLocation } from '../../../js/authSetting';

let locked = false

BasePage({
  pageKey: 'chooseCustomer',
  validateLogin: false,
  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    pageIndex: 1,
    pageSize: 10,
    hasMore: true,
    loaded: false,
    searchKey: '',
    isIphoneX: app.globalData.isIphoneX,
    mainColor: api.titleColor || "#e56b14",
    multiple: true, // 是否多选
    formKey: '', // 上个页面要修改的数据的key
    selectedList: [], // 上个页面传入的, 已选中的列表
    sortList: [{
        id: 0,
        name: '最近拜访时间倒序排列',
        value: '<NoFollowDay>ASC</NoFollowDay>'
      },
      {
        id: 1,
        name: '最近下单时间倒序排列',
        value: '<NoOrderDay>ASC</NoOrderDay>'
      },
      {
        id: 2,
        name: '新增时间倒序排列',
        value: '<AddTime>DESC</AddTime><Id>DESC</Id>'
      },
      {
        id: 3,
        name: '应收金额降序排列',
        value: '<nopayamount>DESC</nopayamount>'
      },
      {
        id: 4,
        name: '距离由近及远排列',
        value: '<Distance>ASC</Distance>'
      },
    ],
    selectedSortIndex: 2,
    filterData: {
      pickerData: []
    },
    filterHidden: ['tag', 'keyword', 'customerWarning'], // filter不显示那些项
    style: 1, // 单选时的显示风格, 1:顶部简单搜索,单选需要二次确认 2:顶部多过滤器,单选直接选择
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('chooseCustomer onload')
    let multiple = true
    let style = 1
    if (options.multiple == false || options.multiple == 'false') {
      multiple = false
    }
    if (options.style == 2) {
      style = 2
    }
    this.setData({
      formKey: options.formKey || '',
      multiple,
      style
    })
    this.getPrevPageData()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  getLocation () {
    let that = this
    getFuzzyLocation({
      success (res) {
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        })
        that.getDataList()
      },
      fail () {
        that.getDataList()
      }
    })
  },

  changeSort(e) {
    this.setData({
      selectedSortIndex: e.detail.value
    })
    this.onPullDownRefresh()
  },

  search(e) {
    this.setData({
      searchKey: e.detail
    })
    this.onPullDownRefresh()
  },

  getPrevPageData() {
    let pages = getCurrentPages()
    let prevPage = pages[pages.length - 2]
    let formKey = this.data.formKey
    let selectedList = []
    let obj = prevPage.data.forms || prevPage.data
    if (Array.isArray(obj)) {
      let index = obj.findIndex((item) => {
        return item.key == formKey
      })
      if (index != -1) {
        selectedList = obj[index].value
      }
    } else {
      selectedList = obj[formKey]
    }
    if (type.isUndefined(selectedList)) {
      selectedList = []
    } else if (!Array.isArray(selectedList)) {
      selectedList = [selectedList]
    }
    this.setData({
      selectedList
    })
    this.getLocation()
  },

  getDataList() {
    let {
      list,
      pageIndex,
      pageSize,
      searchKey,
      sortList,
      selectedSortIndex,
      filterData,
      latitude,
      longitude,
      selectedList
    } = this.data
    let obj = {}
    filterData.pickerData.map((item) => {
      if (item.Id == -1) {
        obj[item.key] = ''
      } else {
        obj[item.key] = item.Id
      }
    })
    let data = {
      pageIndex,
      pageSize,
      searchKey,
      orderBy: sortList[selectedSortIndex].value, // 排序方式
      levelId: obj['customerLevel'], // 客户等级
      typeId: obj['customerType'], // 客户类型
      noOrderDay: obj['noOrderDay'], // 未下单天数
      noFollowDay: obj['noFollowDay'], // 未拜访天数
      arrearsAmount: obj['arrears'], // 是否欠款
      tagId: obj['customerWarning'], // 预警等级
      passed: 1, // 正式客户: 1
      latitude,
      longitude,
      pageType: 0, // 可开单用户
    }
    customer.getCustomerList(data).then((res) => {
      let resList = res.Content.Data
      if (!resList || resList.length == 0) {
        this.setData({
          hasMore: false,
          loaded: true
        })
        wx.stopPullDownRefresh()
        locked = false
        return
      }
      resList = resList.map((item) => {
        let searchIndex = selectedList.findIndex((selectedItem) => {
          return selectedItem.Id == item.Id
        })
        if (searchIndex != -1) {
          item.selected = true
        } else {
          item.selected = false
        }
        return item
      })
      list = [...list, ...resList]
      // console.log(list)
      this.setData({
        list,
        hasMore: true,
        loaded: true
      })
      locked = false
      wx.stopPullDownRefresh()
      if (list.length < 10) {
        this.onReachBottom()
      }
    }).catch((err) => {
      console.log(err);
      this.setData({
        hasMore: false,
        loaded: true
      })
      wx.stopPullDownRefresh()
      locked = false
    })
  },

  showFilter() {
    let that = this
    let customerFilter = this.selectComponent('#customerFilter')
    customerFilter.$$showComponent({
      success(res) {
        console.log('页面获取到的filter数据', res)
        that.setData({
          filterData: res,
          searchKey: res.keyword
        })
        that.onPullDownRefresh()
      },
      fail() {
        console.log('用户关闭');
      }
    })
  },

  toPage(e) {
    let url = e.currentTarget.dataset.url
    router.navigate({
      path: url
    })
  },

  selectUser(e) {
    let {
      list,
      selectedList,
      multiple,
      style
    } = this.data
    let index = e.currentTarget.dataset.index
    if (!multiple) {
      list = list.map((item) => {
        item.selected = false
        return item
      })
      list[index].selected = true
      selectedList = []
    } else {
      // 取反
      list[index].selected = !!!list[index].selected
    }
    if (list[index].selected == false) {
      let selectedIndex = selectedList.findIndex((item) => {
        return item.Id == list[index].Id
      })
      if (selectedIndex != -1) {
        selectedList.splice(selectedIndex, 1)
      }
    }
    this.setData({
      list,
      selectedList
    })
    if (style == 2) {
      this.confirm()
    }
  },

  confirm() {
    let {
      list,
      selectedList
    } = this.data
    let listFilter = list.filter((item) => {
      return item.selected
    })
    selectedList = mergeArray(listFilter, selectedList)
    this.setPrevPageData({
      data: selectedList
    })
  },

  setPrevPageData(e) {
    let pages = getCurrentPages()
    let prevPage = pages[pages.length - 2]
    e.formKey = this.data.formKey
    prevPage.selected(e)
    router.navigateBack()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    console.log('chooseCustomer hide')
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    locked = false
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      list: [],
      pageIndex: 1,
      pageSize: 10,
      hasMore: true,
      loaded: false
    })
    locked = true
    this.getDataList()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    let {
      hasMore,
      pageIndex
    } = this.data
    if (!hasMore) {
      return
    }
    if (locked) {
      return
    }
    locked = true
    this.setData({
      pageIndex: pageIndex + 1
    })
    this.getDataList()
  },

  // /**
  //  * 用户点击右上角分享
  //  */
  // onShareAppMessage() {

  // }
})